import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Button, List, Card, Tag, Input, Modal, Form, message } from 'antd'
import { PlusOutlined } from '@ant-design/icons'
import axios from 'axios'
import './community.styl'

export default function Community() {
  const [bountyList, setBountyList] = useState([])
  const [isPublishModalVisible, setIsPublishModalVisible] = useState(false)
  const [form] = Form.useForm()
  const navigate = useNavigate()

  // 加载悬赏列表
  useEffect(() => {
    const fetchBounties = async () => {
      try {
        const res = await axios.get('/api/v1/bounty-task/list')
        setBountyList(res.data.list || [])
      } catch (error) {
        message.error('悬赏列表加载失败')
      }
    }
    fetchBounties()
  }, [])

  // 发布悬赏提交
  const handlePublish = async (values) => {
    try {
      await axios.post('/api/v1/bounty-task/create', {
        ...values,
        expireAt: new Date(Date.now() + 30 * 86400000).toISOString()  // 默认30天后过期
      })
      message.success('悬赏发布成功')
      setIsPublishModalVisible(false)
      form.resetFields()
      // 刷新列表
      const res = await axios.get('/api/v1/bounty-task/list')
      setBountyList(res.data.list || [])
    } catch (error) {
      message.error(`发布失败：${error.response?.data?.message || '未知错误'}`)
    }
  }

  return (
    <div className="community-container">
      {/* 发布悬赏按钮 */}
      <div className="bounty-actions">
        <Button 
          type="primary" 
          icon={<PlusOutlined />}
          size="large"
          onClick={() => setIsPublishModalVisible(true)}
        >
          发布资源悬赏
        </Button>
      </div>

      {/* 悬赏任务列表 */}
      <List
        dataSource={bountyList}
        bordered
        itemLayout="vertical"
        renderItem={item => (
          <List.Item
            key={item.id}
            actions={[
              <Tag color="blue">{item.category}</Tag>,
              <span>剩余{Math.ceil((new Date(item.expireAt) - Date.now()) / 86400000)}天</span>
            ]}
          >
            <List.Item.Meta
              title={
                <Button 
                  type="link"
                  size="large"
                  onClick={() => navigate(`/bounty/${item.id}`)}  // 跳转悬赏详情页（需后续开发）
                >
                  {item.title}
                </Button>
              }
              description={[
                `奖励：${item.reward}魔力值`,
                `状态：${item.status === 'pending' ? '进行中' : '已完成'}`,
                `发布者：${item.creator?.username || '匿名用户'}`
              ]}
            />
            <div className="bounty-description">
              {item.description}
            </div>
          </List.Item>
        )}
      />

      {/* 发布悬赏弹窗 */}
      <Modal
        title="发布资源悬赏"
        open={isPublishModalVisible}
        onCancel={() => setIsPublishModalVisible(false)}
        width={600}
        footer={[
          <Button key="cancel" onClick={() => setIsPublishModalVisible(false)}>取消</Button>,
          <Button key="publish" type="primary" onClick={() => form.submit()}>发布</Button>
        ]}
      >
        <Form form={form} onFinish={handlePublish} layout="vertical">
          <Form.Item
            name="title"
            label="悬赏标题"
            rules={[{ required: true, message: '请输入标题', max: 50 }]}
          >
            <Input placeholder="例如：求北京交通大学2024年计算机期末试卷" />
          </Form.Item>

          <Form.Item
            name="description"
            label="需求描述"
            rules={[{ required: true, message: '请输入需求描述', max: 500 }]}
          >
            <Input.TextArea rows={4} placeholder="请详细描述资源要求（格式、年份、内容等）" />
          </Form.Item>

          <Form.Item
            name="reward"
            label="奖励魔力值"
            rules={[{ required: true, type: 'number', min: 100, message: '最低100魔力值' }]}
          >
            <Input.Number min={100} max={10000} placeholder="输入奖励金额" />
          </Form.Item>

          <Form.Item
            name="category"
            label="资源分类"
            rules={[{ required: true, message: '请选择分类' }]}
          >
            <Input placeholder="例如：课程资料/考试辅导/软件工具" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  )
}